package com.javaee.wordtree.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javaee.wordtree.entity.ModelChat;
import com.javaee.wordtree.entity.ModelMessage;
import com.javaee.wordtree.mapper.ModelMessageMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 模型消息服务类
 */
@Service
public class ModelMessageService extends ServiceImpl<ModelMessageMapper, ModelMessage> {

    @Resource
    private ModelMessageMapper modelMessageMapper;

    @Resource
    private ModelChatService modelChatService;

    @Resource
    private DeepseekService deepseekService;

    /**
     * 获取聊天的所有消息
     * 
     * @param chatId 聊天ID
     * @return 消息列表
     */
    public List<ModelMessage> getChatMessages(Integer chatId) {
        return modelMessageMapper.findMessagesByChatId(chatId);
    }

    /**
     * 获取聊天的最近几条消息（用于上下文）
     * 
     * @param chatId 聊天ID
     * @param limit  限制的消息数量
     * @return 最近的消息列表（按时间正序排列）
     */
    public List<ModelMessage> getRecentChatMessages(Integer chatId, Integer limit) {
        List<ModelMessage> messages = modelMessageMapper.findRecentMessagesByChatId(chatId, limit);
        // 由于数据库查询是DESC排序，需要反转列表来得到正确的时间顺序
        java.util.Collections.reverse(messages);
        return messages;
    }

    /**
     * 保存用户消息并生成AI回复
     * 
     * @param chatId 聊天ID
     * @param text   用户发送的消息文本
     * @return AI回复的消息对象
     */
    @Transactional(rollbackFor = Exception.class)
    public ModelMessage saveMessageAndGenerateReply(Integer chatId, String text) {
        // 1. 保存用户消息
        ModelMessage userMessage = new ModelMessage();
        userMessage.setChatId(chatId);
        userMessage.setText(text);
        userMessage.setIsUser(true);
        userMessage.setCreatedTime(new Date());
        save(userMessage);

        // 2. 更新聊天的最后更新时间
        modelChatService.updateChatTime(chatId);

        // 3. 获取会话信息，以确定如何生成回复
        ModelChat chat = modelChatService.getChatById(chatId);

        // 4. 根据聊天类型生成AI回复
        String replyText = generateReply(chat, text);

        // 5. 保存AI回复
        ModelMessage aiMessage = new ModelMessage();
        aiMessage.setChatId(chatId);
        aiMessage.setText(replyText);
        aiMessage.setIsUser(false);
        aiMessage.setCreatedTime(new Date());
        save(aiMessage);

        return aiMessage;
    }

    /**
     * 重新生成指定消息的AI回复（替换该消息并删除后续所有对话）
     * 
     * @param messageId 要重新生成的消息ID
     * @return 新生成的AI回复消息对象
     */
    @Transactional(rollbackFor = Exception.class)
    public ModelMessage regenerateMessage(Integer messageId) {
        // 1. 获取要重新生成的消息
        ModelMessage originalMessage = getById(messageId);
        if (originalMessage == null) {
            throw new RuntimeException("找不到指定的消息");
        }

        if (originalMessage.getIsUser()) {
            throw new RuntimeException("不能重新生成用户消息");
        }

        Integer chatId = originalMessage.getChatId();

        // 2. 获取该消息的创建时间
        String messageCreatedTime = modelMessageMapper.getMessageCreatedTime(messageId);

        // 3. 删除该消息及其之后的所有消息
        int deletedCount = modelMessageMapper.deleteMessagesByTimeAndAfter(chatId, messageCreatedTime);
        System.out.println("删除消息数量: " + deletedCount + ", chatId: " + chatId + ", messageId: " + messageId);

        // 4. 找到该AI消息对应的用户消息内容
        List<ModelMessage> messages = getChatMessages(chatId);
        String userText = "";
        for (int i = messages.size() - 1; i >= 0; i--) {
            if (messages.get(i).getIsUser()) {
                userText = messages.get(i).getText();
                break;
            }
        }

        // 5. 更新聊天的最后更新时间
        modelChatService.updateChatTime(chatId);

        // 6. 获取会话信息，以确定如何生成回复
        ModelChat chat = modelChatService.getChatById(chatId);

        // 7. 根据聊天类型生成新的AI回复
        String replyText = generateReply(chat, userText);

        // 8. 保存新的AI回复
        ModelMessage newAiMessage = new ModelMessage();
        newAiMessage.setChatId(chatId);
        newAiMessage.setText(replyText);
        newAiMessage.setIsUser(false);
        newAiMessage.setCreatedTime(new Date());
        save(newAiMessage);

        return newAiMessage;
    }

    // /**
    // * 重新生成最后一条AI回复
    // *
    // * @param chatId 聊天ID
    // * @return 新生成的AI回复消息对象
    // */
    // @Transactional(rollbackFor = Exception.class)
    // public ModelMessage regenerateLastReply(Integer chatId) {
    // // 1. 获取最后一条AI回复消息
    // List<ModelMessage> messages = getChatMessages(chatId);
    // ModelMessage lastAiMessage = null;

    // for (int i = messages.size() - 1; i >= 0; i--) {
    // if (!messages.get(i).getIsUser()) {
    // lastAiMessage = messages.get(i);
    // break;
    // }
    // }

    // if (lastAiMessage == null) {
    // throw new RuntimeException("找不到可重新生成的AI回复");
    // }

    // return regenerateMessage(lastAiMessage.getId());
    // }

    /**
     * 生成英语对话回复
     * 
     * @param chat      聊天上下文
     * @param userInput 用户输入
     * @return 生成的回复
     */
    private String generateEnglishReply(ModelChat chat, String userInput) {
        try {
            // 获取最近的8条历史对话记录以提供上下文（4轮对话）
            List<ModelMessage> chatHistory = getRecentChatMessages(chat.getChatId(), 8);

            // 根据聊天设置和历史记录构建合适的提示词
            String difficulty = chat.getDifficulty() != null ? chat.getDifficulty() : "medium";
            String keywords = chat.getKeywords();
            String prompt = buildEnglishPromptWithContext(difficulty, keywords, userInput, chatHistory);

            // 调用DeepSeek API
            return deepseekService.callDeepseekApi(prompt)
                    .map(response -> {
                        if (response.getChoices() != null && !response.getChoices().isEmpty()) {
                            return response.getChoices().get(0).getMessage().getContent();
                        }
                        return "Sorry, I couldn't generate a response right now.";
                    })
                    .onErrorReturn("Sorry, there was an error generating a response. Please try again later.")
                    .block(); // 阻塞获取结果
        } catch (Exception e) {
            return "An error occurred while processing your message. Please try again later.";
        }
    }

    /**
     * 构建包含对话历史上下文的英语对话提示词
     * 
     * @param difficulty  难度级别
     * @param keywords    关键词/主题
     * @param userInput   用户输入
     * @param chatHistory 对话历史记录
     * @return 构建的提示词
     */
    private String buildEnglishPromptWithContext(String difficulty, String keywords, String userInput,
            List<ModelMessage> chatHistory) {
        StringBuilder promptBuilder = new StringBuilder(); // 定义角色和目标
        promptBuilder.append("You are a friendly English conversation partner helping users practice their English. ");
        promptBuilder.append(
                "Respond to the user's message in a natural, conversational way based on the context of our conversation. ");

        // 设置难度级别
        if ("easy".equalsIgnoreCase(difficulty)) {
            promptBuilder.append("Use simple vocabulary and short sentences suitable for beginners. ");
            promptBuilder.append("Speak slowly and clearly, using basic English expressions. ");
            promptBuilder.append(
                    "At the end of your response, add an encouraging prompt in this format: *(Remember, you can tell me about your feelings!)* to guide the user to continue the conversation with simple topics. ");
        } else if ("hard".equalsIgnoreCase(difficulty)) {
            promptBuilder.append("Use advanced vocabulary, idioms, and complex sentence structures. ");
            promptBuilder.append("Speak at a natural pace using sophisticated English expressions. ");
            promptBuilder.append(
                    "At the end of your response, add a thought-provoking prompt in this format: *(Perhaps you could elaborate on your perspective regarding this matter?)* to encourage deeper, more complex discussions. ");
        } else { // medium (default)
            promptBuilder.append(
                    "Use moderate vocabulary and varied sentence structures suitable for intermediate learners. ");
            promptBuilder.append("Speak at a moderate pace using common English expressions. ");
            promptBuilder.append(
                    "At the end of your response, add a friendly prompt in this format: *(What do you think about this, or would you like to share more?)* to encourage continued conversation at an intermediate level. ");
        }

        // 添加关键词/主题引导
        if (keywords != null && !keywords.isEmpty()) {
            promptBuilder.append("Try to incorporate or discuss topics related to: ").append(keywords).append(". ");
        }

        // 添加对话历史上下文
        if (chatHistory != null && !chatHistory.isEmpty()) {
            promptBuilder.append("\n\nConversation history:\n");

            for (ModelMessage message : chatHistory) {
                if (message.getIsUser()) {
                    promptBuilder.append("User: ").append(message.getText()).append("\n");
                } else {
                    promptBuilder.append("Assistant: ").append(message.getText()).append("\n");
                }
            }
        }

        // 添加当前用户输入
        promptBuilder.append("\nCurrent user message: \"").append(userInput).append("\"\n");
        promptBuilder.append("Please respond naturally and contextually to continue our conversation.");

        return promptBuilder.toString();
    }

    /**
     * 根据聊天类型生成AI回复
     * 
     * @param chat      聊天上下文
     * @param userInput 用户输入
     * @return 生成的回复
     */
    private String generateReply(ModelChat chat, String userInput) {
        String chatType = chat.getChatType();
        if (chatType == null) {
            chatType = "english"; // 默认为英语对话
        }

        switch (chatType.toLowerCase()) {
            case "english":
                return generateEnglishReply(chat, userInput);
            // case "memory":
            // return generateMemoryReply(chat, userInput);

            default:
                return generateEnglishReply(chat, userInput); // 默认使用英语对话逻辑
        }
    }

    // /**
    // * 生成记忆训练回复
    // *
    // * @param chat 聊天上下文
    // * @param userInput 用户输入
    // * @return 生成的回复
    // */
    // private String generateMemoryReply(ModelChat chat, String userInput) {
    // try {
    // // 获取最近的对话历史
    // List<ModelMessage> chatHistory = getRecentChatMessages(chat.getChatId(), 6);

    // // 构建记忆训练的提示词
    // String difficulty = chat.getDifficulty() != null ? chat.getDifficulty() :
    // "medium";
    // String keywords = chat.getKeywords();
    // String prompt = buildMemoryPromptWithContext(difficulty, keywords, userInput,
    // chatHistory);

    // return deepseekService.callDeepseekApi(prompt)
    // .map(response -> {
    // if (response.getChoices() != null && !response.getChoices().isEmpty()) {
    // return response.getChoices().get(0).getMessage().getContent();
    // }
    // return "Sorry, I couldn't generate a memory training response right now.";
    // })
    // .onErrorReturn("Sorry, there was an error generating a response. Please try
    // again later.")
    // .block();
    // } catch (Exception e) {
    // return "An error occurred while processing your message. Please try again
    // later.";
    // }
    // }

    // /**
    // * 构建包含对话历史上下文的记忆训练提示词
    // */
    // private String buildMemoryPromptWithContext(String difficulty, String
    // keywords, String userInput,
    // List<ModelMessage> chatHistory) {
    // StringBuilder promptBuilder = new StringBuilder();

    // promptBuilder.append("You are an AI assistant specialized in memory training
    // and cognitive exercises. ");
    // promptBuilder.append("Help users improve their memory through interactive
    // exercises, games, and techniques. ");
    // promptBuilder.append("Provide personalized memory training based on the
    // conversation context. ");
    // if ("easy".equalsIgnoreCase(difficulty)) {
    // promptBuilder.append("Use simple memory exercises suitable for beginners. ");
    // promptBuilder.append("Focus on basic recall and recognition tasks. ");
    // promptBuilder.append(
    // "Include teaching prompts in your responses using the format *(Remember, you
    // can tell me about your day!)* to guide and encourage users. ");
    // } else if ("hard".equalsIgnoreCase(difficulty)) {
    // promptBuilder.append("Use advanced memory techniques and complex cognitive
    // challenges. ");
    // promptBuilder.append("Include multiple memory systems and advanced mnemonics.
    // ");
    // } else {
    // promptBuilder.append("Use intermediate memory exercises with moderate
    // complexity. ");
    // promptBuilder.append("Balance between recall, recognition, and working memory
    // tasks. ");
    // }

    // if (keywords != null && !keywords.isEmpty()) {
    // promptBuilder.append("Focus on memory training related to:
    // ").append(keywords).append(". ");
    // }

    // if (chatHistory != null && !chatHistory.isEmpty()) {
    // promptBuilder.append("\n\nPrevious memory training conversation:\n");
    // for (ModelMessage message : chatHistory) {
    // if (message.getIsUser()) {
    // promptBuilder.append("User: ").append(message.getText()).append("\n");
    // } else {
    // promptBuilder.append("Assistant: ").append(message.getText()).append("\n");
    // }
    // }
    // }

    // promptBuilder.append("\nCurrent user message:
    // \"").append(userInput).append("\"\n");
    // promptBuilder
    // .append("Please respond with appropriate memory training guidance or
    // exercises based on the context.");

    // return promptBuilder.toString();
    // }

}